
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Diagnostics;

using Swaf;
using Swaf.BizRule;
using Swaf.Container;

namespace Swaf.BizRule.ThreadedQueue
{
	/// <summary>
	/// Summary description for BaseInitialRequest.
	/// </summary>
	public class BaseInitialRequest : ResultsRuleGroup, IInitialRequest, IRuleGroup, IRuleGroupControl
	{
		protected static ulong s_baseIdIndex = 0;
		internal static int DefaultMinWorkers = 3;
		internal static int DefaultMaxWorkers = -1;

		protected int m_minWorkers = DefaultMinWorkers;
		protected int m_maxWorkers = DefaultMaxWorkers;

		protected RuleQueue m_ruleQueue;
		protected IApplication m_app;
		protected LinkedList.NodeRef m_ruleQueueWaitingPos;
		protected LinkedList m_internalQueue;
		protected uint m_queuedCount = 0;
		protected IDictionary m_workers;

		protected ulong m_id = 0;

		public BaseInitialRequest(IApplication app)
			:this(DefaultMinWorkers, DefaultMaxWorkers)
		{
			m_app = app;
		}
		
		public BaseInitialRequest(int minWorkers, int maxWorkers)
			:base(null)
		{
			m_id = calcNextRuleCallId();
			m_ruleQueue = (RuleQueue)BasicExecutor.RuleQueue;
			m_minWorkers = minWorkers;
			m_maxWorkers = maxWorkers;
		}

		#region IInitialRequest Members
		public ulong Id {get{return m_id;}}
		public int MinWorkers {get{return m_minWorkers;}set{m_minWorkers = value;}}
		public int MaxWorkers {get{return m_maxWorkers;}set{m_maxWorkers = value;}}
		public uint ActiveRuleCount	{get{return (uint)m_workers.Count;}}
		public IApplication App {get{return m_app;}}
		public uint EnqueuedRuleCount {get{return m_queuedCount;}}
			#endregion

			#region IRuleGroup Members
			public override IInitialRequest MainRequest {get{return this;}}

		#endregion

		#region Worker Management Members
		internal QueueElement dequeue(Worker w, bool addWorkerToListOfWorkers)
		{
			QueueElement el  = null;
			lock(InternalQueue)
			{
				if(InternalQueue.Tail == null)
				{
					return null;
				}
				el = (QueueElement)InternalQueue.Tail.Element;
				--m_queuedCount;
				InternalQueue.remove(InternalQueue.Tail);
				el.RulesetQueuePos = null;
				//MJD5: m_ruleQueue.pullFromRuleQueue(el);
			}
			if(addWorkerToListOfWorkers)
				addWorker(w);
			return el;
		}

		internal LinkedList.NodeRef QueueWaitingPos
		{
			get{return m_ruleQueueWaitingPos;}
			set{m_ruleQueueWaitingPos = value;}
		}

		internal bool NeedMoreThreads
		{
			get
			{
				bool needThem = false;
				if(InternalQueue.Head != null  && Workers.Count < MinWorkers)
					needThem = true;
				return needThem;
			}
		}

		protected internal uint calcNumThreadsNeeded(bool useMax)
		{
			int start = useMax?MaxWorkers:MinWorkers;
			if(start == -1)
				start = int.MaxValue;
			int numNeeded = start - Workers.Count;
			if(numNeeded > m_queuedCount)
				numNeeded = (int)m_queuedCount;
			return (uint)(numNeeded<0?0:numNeeded);
		}

		internal void addRule(QueueElement el)
		{
			lock(InternalQueue)
			{
				++m_queuedCount;
				//++m_totalRules; //this is now managed by the BasicRuleGroupClass
				el.RulesetQueuePos = InternalQueue.addHead(el);
			}
		}

		internal void pullFromRuleQueue(QueueElement el, Worker w)
		{
			lock(InternalQueue)
			{
				--m_queuedCount;
				InternalQueue.remove(el.RulesetQueuePos);
				if(w != null)
					addWorker(w);
			}
		}

		internal BaseInitialRequest removeWorker(Worker w)
		{
			// Moved this to be calculated before the Workers lock because it appears
			// that a deadlock was occuring due to the fact that calNumNeededThreads locks
			// using another object and in a high volume situation two different threads could
			// be holding these lockss
			uint numThreadsNeeded = m_ruleQueue.calcNumNeededThreads();

			lock(Workers)
			{
				displayDebugInfo("-");
				int workerCount = Workers.Count;
				if(InternalQueue.Head != null &&
					(workerCount <= MinWorkers ||
					(workerCount <= MaxWorkers && numThreadsNeeded == 0)))
					return this;
				else
				{
					Workers.Remove(w);
					return null;
				}
			}
		}

		private void addWorker(Worker w)
		{
			lock(Workers)
			{
				Workers[w] = w;
				displayDebugInfo("+");
			}
		}

		protected void displayDebugInfo(string prefix)
		{
			Debug.WriteLine(String.Format("{0}: {1} InitialRequest Worker Count: {2} - Total Rules: {3} - Rules Completed: {4}",
				m_id, prefix, Workers.Count, MinWorkers, RulesCompletedCount));
		}
		#endregion



		private static ulong calcNextRuleCallId()
		{
			return ++s_baseIdIndex;
		}

		protected LinkedList InternalQueue
		{
			get
			{
				if(m_internalQueue == null)
					lock(this)
					{
						if(m_internalQueue == null)
							m_internalQueue = new LinkedList();
					}
				return m_internalQueue;
			}
		}

		protected IDictionary Workers
		{
			get
			{
				if(m_workers == null)
					lock(this)
					{
						if(m_workers == null)
							m_workers = new Hashtable();
					}
				return m_workers;
			}
		}



	}
}
